# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  include ApplicationHelper 
  protect_from_forgery # See ActionController::RequestForgeryProtection for details
  before_filter :current_user,:find_recent_comments,:find_all_categories,:find_friend_links,:find_archive_tree,:find_recent_visited_users,:find_show_widgets
  helper_method :current_user_session, :current_user
  after_filter :expire_fragment_cache, :only => [:create,:update,:destroy], :if => Proc.new {|c| c.class.private_method_defined? :expire_fragment_cache} # => 清除片段缓存
  layout :set_layout
  
  private
  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end

  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.record
  end

  def require_admin
    unless is_admin?
      store_location
      flash[:notice] = "您无权进入！"
      redirect_to root_url
      return false
    end
  end

  def require_user
    unless current_user
      store_location
      flash[:notice] = "请先登录！"
      redirect_to new_user_session_url
      return false
    end
  end

  def require_no_user
    if current_user
      store_location
      flash[:notice] = "请先登录！"
      redirect_to user_url(current_user)
      return false
    end
  end

  def store_location
    session[:return_to] = request.request_uri
  end

  def redirect_back_or_default(default)
    redirect_to(session[:return_to] || default)
    session[:return_to] = nil
  end

  # => 找到所有分类
  def find_all_categories
    @categories = Category.all(:order => "rank")
  end

  # => 找到最近10条评论
  def find_recent_comments
    @recent_comments = Comment.recent_comments
  end

  # => 日志归档
  def find_archive_tree
    @archives = Post.all(:select => "DATE_FORMAT(created_at,\"%Y-%m\") AS date,COUNT(*) AS count", :group => "DATE_FORMAT(created_at,\"%Y-%m\")")
  end
  # => 友情链接
  def find_friend_links
    @friend_links = FriendLink.passed_firend_links
  end
  # => 最近活跃访客
  def find_recent_visited_users
    @recent_visited_users = User.recent_visited_users
  end

  # => 查找可现实的小工具
  def find_show_widgets
    @show_widgets = Widget.find_show_widgets
  end

  # => 设置整个网站的布局
  def set_layout
    params[:controller] == "admin" ? "admin" : nil
  end

end
